package org.laizili.solution.leetcode;

/**
 * <a href="https://leetcode.cn/problems/validate-ip-address/">468. 验证IP地址</a>
 * <p>
 * tags: 字符串模拟;
 * <p>
 * notes:
 * 对{@link String}类{@linkplain String#indexOf(int, int)}、{@linkplain String#split(String, int)}两个方法的应用
 */
public class Problem468 {
    private static class Solution {
        public String validIPAddress(String queryIP) {
            // 考察：
            //   String.indexOf(ch,offset)
            //   String.split(splitter,limit)
            // 方法的理解
            if (queryIP.indexOf('.') > 0) {
                //ipv4
                int cur = 0;
                int cut;
                for (int i = 0; i < 4; i++) {
                    // lastToken
                    cut = i < 3 ? queryIP.indexOf('.', cur) : queryIP.length();
                    int tokenLength = cut - cur;
                    if (tokenLength <= 0 || tokenLength > 3) {
                        return invalid;
                    }
                    if (tokenLength > 1 && queryIP.charAt(cur) == '0') {
                        return invalid;
                    }
                    int num = 0;
                    for (int j = cur; j < cut; j++) {
                        if (!Character.isDigit(queryIP.charAt(j))) {
                            return invalid;
                        }
                        num = num * 10 + queryIP.charAt(j) - '0';
                    }
                    if (num > 255) {
                        return invalid;
                    }
                    cur = cut + 1;
                }
                return ipv4;
            } else {
                // ipv6
                int cur = 0;
                int cut;
                for (int i = 0; i < 8; i++) {
                    cut = i < 7 ? queryIP.indexOf(':', cur) : queryIP.length();
                    int tokenLength = cut - cur;
                    if (tokenLength < 1 || tokenLength > 4) {
                        return invalid;
                    }
                    for (int j = cur; j < cut; j++) {
                        char ch = queryIP.charAt(j);
                        if (!(Character.isDigit(ch) || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F')) {
                            return invalid;
                        }
                    }
                    cur = cut + 1;
                }
                return ipv6;
            }
        }

        private final static String ipv4 = "IPv4";
        private final static String ipv6 = "IPv6";
        private final static String invalid = "Neither";
    }


    public static void main(String[] args) {
        System.out.println(new Solution().validIPAddress("0::85a3:0:0:8A2E:0370:7334"));
    }
}
